<template>
  <div>
    <div>
      <!--顶部搜索 -->
      <div class="top-operate">
        <div>
          <div>
            <el-select class="select-class" v-model="order.textCol">
              <el-option label="订单号" value="orderNo"></el-option>
              <el-option label="收货人" value="customerNickname"></el-option>
              <el-option label="收货人电话" value="customerPhone"></el-option>
              <el-option label="商品名称" value="goodsTitle"></el-option>
              <el-option :label="getVersionType() == 5 ? '团长名称' : '分销商名称'" value="memberNickname"></el-option>
              <el-option :label="getVersionType() == 5 ? '团长电话' : '分销商电话'" value="memberPhone"></el-option>
            </el-select>
            <el-input style="width: 200px;margin-left: 15px" v-model="order.textValue" placeholder="请输入内容"></el-input>
            <el-select class="select-class pad-l-10" v-model="order.timeCol" style="margin-right: 10px">
              <el-option label="下单时间" value="createTime"></el-option>
              <el-option label="付款时间" value="payTime"></el-option>
              <el-option label="发货时间" value="deliveryTime"></el-option>
              <el-option :label="getVersionType() == 5 ? '提货时间' : '收货时间'" value="receivedTime"></el-option>
              <el-option label="取消时间" value="cancelTime"></el-option>
              <el-option label="完成时间" value="completeTime"></el-option>
            </el-select>
            <el-date-picker class="pad-l-10" v-model="order.timeValue" type="datetimerange" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <el-autocomplete class="inline-input" v-model="order.village" :fetch-suggestions="queryVillage" placeholder="请选择/输入小区名称" @select="onSelectVillage" @input="onClearVillage" v-if="getVersionType() == 5">
            </el-autocomplete>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </div>
          <span style="font-size: 18px">合计产生金额：<span style="color: red">￥{{ countAmount }}</span></span>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="orderList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中" style="width: 100%">
          <el-table-column min-width="300px" label="订单信息" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p" @click="showDetail(scope.row)">
                <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl" class="user-avatar"></label>
                <div class="font-14 pad-l-10">
                  <div v-if="scope.row.goodsTitle.length <= 20">{{scope.row.goodsTitle}}</div>
                  <div v-if="scope.row.goodsTitle.length > 20">{{scope.row.goodsTitle.slice(0,20) + '...'}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="订单号" prop="orderNo"></el-table-column>
          <el-table-column min-width="180px" label="收货人">
            <template slot-scope="scope">
              <div v-if="scope.row.customerNickname">
                <div>{{scope.row.customerNickname}}</div>
                <div v-if="scope.row.customerPhone">{{scope.row.customerPhone}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="120px" label="数量" prop="goodsNum">
          </el-table-column>
          <el-table-column v-if="false" min-width="150px" label="零售价">
            <template slot-scope="scope">
              <div v-if="scope.row.goodsAmount">
                <div>￥{{scope.row.goodsAmount}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="实付金额" prop="actualPrice" v-if="getVersionType() != 2">
            <template slot-scope="scope">
              <div v-if="scope.row.actualPrice">
                <div>￥{{scope.row.actualPrice}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="150px" prop="memberCardCommission" v-if="false">
            <template slot="header" slot-scope="scope">
              <span>微客佣金</span>
            </template>
            <template slot-scope="scope">
              <template>
                {{ scope.row.memberCardCommission ? '￥' + scope.row.memberCardCommission : ''}}
              </template>
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="实收金额" prop="enterpriseAmount" v-if="getVersionType() != 2">
            <template slot-scope="scope">
              <div v-if="scope.row.enterpriseAmount">
                <div>￥{{scope.row.enterpriseAmount}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="200px">
            <template slot="header" slot-scope="scope">
              <span>{{orderTimeColName}}</span>
            </template>
            <template slot-scope="scope">
              {{ scope.row[orderTimeCol]}}
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="订单状态" v-if="order.orderStatus == 100">
            <template slot-scope="scope">
              <template>
                {{ getVersionType() == 5 ? dict.villageOrderStatus[scope.row.orderStatus] : dict.orderStatus[scope.row.orderStatus] }}
              </template>
            </template>
          </el-table-column>
          <el-table-column min-width="140px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="showDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import { pagingMemberProjectOrder, countMemberProjectOrder } from '@/api/goods/order'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import { listVillageByEnterpriseId } from '@/api/user/village'
  import { downloadFile } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },
    props: {
      memberId: {
        type: String
      }
    },
    data() {
      return {
        countAmount: 0,
        promotionId: '',
        recruiterId: '',
        multipleSelection: [],
        total: 0,
        listLoading: true,
        searchListQuery: {},
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          orderType: 30,
          currentPage: 1,
          size: 10
        },
        order: {
          orderStatus: '1',
          timeCol: 'createTime',
          timeValue: [],
          textCol: 'orderNo',
          textValue: ''
        },
        dict: {
        },
        orderList: [],
        labels: {
          '0': '待付款(0)',
          '1': '待发货(0)',
          '2': '待收货(0)',
          '3': '已收货(0)',
          '4': '已完成(0)',
          '-2': '已取消(0)',
          '100': '全部订单(0)'
        },
        villageList: [],
        orderTimeColName: '时间',
        orderTimeColNames: {
          '0': '下单时间',
          '1': '支付时间',
          '2': '发货时间',
          '4': '完成时间'
        },
        orderTimeCol: 'createTime',
        orderTimeCols: {
          '0': 'createTime',
          '1': 'payTime',
          '2': 'deliveryTime',
          '4': 'completeTime'
        },
        showStatOrder: 1
      }
    },
    // 初始化页面
    created() {
      const queryParams = this.getCurrentPage().query
      if (queryParams.promotionId) {
        this.promotionId = queryParams.promotionId
      }
      if (queryParams.recruiterId) {
        this.recruiterId = queryParams.recruiterId
      }
      if (queryParams.timeCol) {
        this.order.timeCol = queryParams.timeCol
      }
      if (queryParams.startEndTime) {
        this.order.timeValue = queryParams.startEndTime
      }
      if (queryParams.orderStatus) {
        this.order.orderStatus = queryParams.orderStatus
      }
      if (queryParams.showStatOrder === '0') {
        this.showStatOrder = 0
      }
      if (this.getVersionType() * 1 === 5) {
        this.order.timeCol = 'payTime'
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseConfig = response.data
          const statTime = new Date()
          statTime.setHours(21)
          statTime.setMinutes(0)
          statTime.setSeconds(0)
          if (this.enterpriseConfig && this.enterpriseConfig.orderStatTime) {
            const times = this.enterpriseConfig.orderStatTime.split(':')
            statTime.setHours(times[0])
            statTime.setMinutes(times[1])
            statTime.setSeconds(times[2])
          }
          this.order.timeValue = [
            statTime.getFullYear() + '-' + (statTime.getMonth() + 1) + '-' + (statTime.getDate() - 1) + ' ' + statTime.getHours() + ':' + statTime.getMinutes() + ':' + statTime.getSeconds(),
            statTime.getFullYear() + '-' + (statTime.getMonth() + 1) + '-' + (statTime.getDate()) + ' ' + statTime.getHours() + ':' + statTime.getMinutes() + ':' + statTime.getSeconds()
          ]
          this.init()
        })
      }

      listVillageByEnterpriseId(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.villageList = response.data
        this.villageList.forEach(village => {
          village.value = village.villageName
        })
      })
      this.searchListQuery = { ...this.defaultQuery }
      this.init()
    },
    methods: {
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.init()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.init()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      setSearchListQuery() {
        // 搜索状态
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.page = currentPage
        this.searchListQuery.size = size
        this.searchListQuery.dateColumn = this.order.timeCol
        this.searchListQuery.startDate = (this.order.timeValue && this.order.timeValue.length > 0) ? this.order.timeValue[0] : ''
        this.searchListQuery.endDate = (this.order.timeValue && this.order.timeValue.length > 1) ? this.order.timeValue[1] : ''
        this.searchListQuery[this.order.textCol] = this.order.textValue
        this.orderTimeColName = this.orderTimeColNames[this.searchListQuery.orderStatus + '']
        if (!this.orderTimeColName) {
          this.orderTimeColName = '时间'
        }
        this.orderTimeCol = this.orderTimeCols[this.searchListQuery.orderStatus + '']
        if (!this.orderTimeCol) {
          this.orderTimeCol = 'createTime'
        }
        this.searchListQuery.memberVillageId = this.order.memberVillageId
        this.searchListQuery.promotionId = this.promotionId
        this.searchListQuery.recruiterId = this.recruiterId
      },
      init() {
        this.setSearchListQuery()
        this.searchListQuery.memberId = this.memberId
        pagingMemberProjectOrder(this.searchListQuery).then(response => {
          if (response.isError) {
            return
          }
          this.total = response.data.total
          this.orderList = response.data.records
          this.orderList.forEach(order => {
            switch (order.orderStatus) {
              default:
              case -2:
              case -1:
              case 0:
                order.orderStatusType = 'danger'
                break
              case 1:
              case 2:
                order.orderStatusType = 'warning'
                break
              case 3:
              case 4:
                order.orderStatusType = 'success'
                break
            }
          })
          this.dict = response.data.dict
          this.listLoading = false
        })
        countMemberProjectOrder(this.searchListQuery).then(response => {
          if (response.isError) return
          this.countAmount = response.data.countAmount
        })
      },
      orderStatusClick() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      showDetail(row) {
        this.$router.push({ path: '/order/order/detail/index', query: { orderId: row.orderId }})
      },
      exportOrder() {
        if (this.multipleSelection.length > 0) {
          const orderIds = this.multipleSelection.map(item => item.orderId)
          downloadFile('/goods/projectOrder/exportOrder', { enterpriseId: this.getEnterpriseId(), orderIds: orderIds.join(',') }, '分销订单.xlsx')
        } else {
          const params = { enterpriseId: this.getEnterpriseId(), orderType: 30 }
          this.setSearchListQuery()
          Object.assign(params, this.searchListQuery)
          downloadFile('/goods/projectOrder/exportOrder', params, '分销订单.xlsx')
        }
      },
      handleSearch() {
        this.init()
      },
      resetSearch() {
        this.searchListQuery = { ... this.defaultQuery }
        this.order = {
          orderStatus: '1',
          timeCol: 'createTime',
          timeValue: [],
          textCol: 'orderNo',
          textValue: '',
          village: '',
          memberVillageId: '',
          currentPage: 1,
          size: 10
        }
        this.init()
      },
      onSelectVillage(item) {
        this.order.memberVillageId = item.villageId
      },
      onClearVillage() {
        if (this.order.village.trim() === '') {
          // 清空小区搜索时，置空memberVillageId
          this.order.memberVillageId = ''
        }
      },
      queryVillage(queryString, cb) {
        const results = queryString ? this.villageList.filter((village) => {
          return (village.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0)
        }) : this.villageList
        // 调用 callback 返回建议列表的数据
        cb(results)
      }
    }
  }
</script>

<style lang="less" scoped>
  .select-class {
    margin-right: -5px;
    width: 120px;
  }
  .user-avatar {
    width: 90px;
    height: 90px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
</style>